package com.hz.house.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.house.bean.entity.CustomerBean;
import com.hz.house.config.TencentImMessageConfig;
import com.hz.house.utils.im_sign.TlsSigature;
import lombok.extern.slf4j.Slf4j;

/**
 * 	腾讯IM通信的业务封装
 * @author lfw
 */
@Service("tCIMService")
@Slf4j
public class TCIMService {

	@Autowired
	private TencentImMessageConfig imConfig;
	
	@Resource
	private RestTemplate restTemplate;
	
	/**
	 * <p> 将用户加入到im通信中
	 * <p> 加入的时机为 获得用户的授权获取用户基本信息后
	 * @param user
	 * @return
	 */
	public Boolean addCustomerTencentYunIm(CustomerBean user) {
		
        // 获取管理员的签名
        TlsSigature.GenTlsSignatureResult result = TlsSigature.genSig(imConfig.getSdkAppId(),
        		imConfig.getAdmin(), 3600 * 24 * 180,imConfig.getSecretKey());
        //请求参数封装
        Map<String, Object> m = new HashMap<>(3);
        m.put("FaceUrl", user.getHeadImg());
        m.put("Nick", user.getName());
        m.put("Identifier", user.getId().toString());
        //发送post请求加入到聊天列表
        String url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?" +
                "usersig=" + result.urlSig + "&apn=1&identifier=" +
        		imConfig.getAdmin() + "&sdkappid=" +imConfig.getSdkAppId() + "&contenttype=json";
        String str = doPostSendMsg(JSON.toJSONString(m),url);
        log.info("将用户加入IM通信用户结果：" + str);
        try {
			JSONObject jsonObject = JSON.parseObject(str);
			String status = jsonObject.getString("ActionStatus");
			return "OK".equals(status);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("用户加入im通信结果转json失败",e);
			return false;
		}
	}
	
	/**封装http请求发送post,返回接口的结果 */
	private String doPostSendMsg(String jsonData,String url) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers);
		String json = restTemplate.postForObject(url, entity, String.class);
		return json;
	}
}
